package com.taxi.driver.module.order.setting;


import android.util.Log;

import com.qianxx.utils.RxUtil;
import com.taxi.driver.R;
import com.taxi.driver.common.BasePresenter;
import com.taxi.driver.config.RemindType;
import com.taxi.driver.data.duty.DutyRepository;
import com.taxi.driver.data.entity.OrderListenerEntity;
import com.taxi.driver.data.user.UserRepository;
import com.taxi.driver.module.vo.TimeVO;
import com.taxi.driver.widget.select.TimeDialog;

import java.util.Calendar;

import javax.inject.Inject;

/**
 * 功能描述：
 */
public class OrderSettingPresenter extends BasePresenter implements OrderSettingContract.Presenter {

    //private final static String TimeFormat = "dd日HH时";
    OrderSettingContract.View mView;
    DutyRepository mDutyRepository;
    UserRepository mUserRepository;

    OrderListenerEntity mEntity;
    TimeVO mStartVO;
    TimeVO mEndVO;

    @Inject
    public OrderSettingPresenter(DutyRepository dutyRepository,
                                 UserRepository userRepository,
                                 OrderSettingContract.View view) {
        mDutyRepository = dutyRepository;
        mUserRepository = userRepository;
        mView = view;
    }

    public void onCreate() {
        mEntity = mDutyRepository.getListenerSetting(mUserRepository.getLocalDriverUuid());
        int remindType = mEntity.getRemindType();
        mView.setSsConfigPosition(getRelatedPosition(remindType));
        mView.setAppointTimeDisplay(remindType);
        /* 判断"开始时间"和"结束时间"，并和当前时间判断 */
        mStartVO = TimeVO.createFrom(mEntity.getStartTime());
        mEndVO = TimeVO.createFrom(mEntity.getEndTime());
        long currentTime = System.currentTimeMillis();
        if (mStartVO != null && currentTime > mStartVO.timeStmap) {
            mStartVO = null; //当前时间大于开始时间，将mStartVO置空
        }
        if (mEndVO != null && currentTime > mEndVO.timeStmap) {
            mEndVO = null; //当前时间大于结束时间，将mEndVO置空
        }
        /* 控制预约时间段的显示 */
        mView.changeStart(mStartVO == null ? "" : mStartVO.getStrTime());
        mView.changeEnd(mEndVO == null ? "" : mEndVO.getStrTime());
    }

    /**
     * 获取对应的position
     *
     * @param remindType
     * @return
     */
    private int getRelatedPosition(int remindType) {
        if (remindType == RemindType.REALTIME) {
            return 0;
        } else if (remindType == RemindType.APPOINT) {
            return 1;
        } else if(remindType == RemindType.RENT){
            return 2;
        } else {
            return 3;
        }
    }

    public void onDestory() {
        //暂未使用
    }

    @Override
    public void selectRemindType(int remindType) {
        mEntity.remindType = remindType; //改变听单偏好
        Log.i("pop--",mEntity.remindType+"");
        mView.setAppointTimeDisplay(mEntity.remindType); //刷新界面显示
    }

    @Override
    public void selectStart() {
        new TimeDialog(mView.getContext(), (dialog, vo) -> {
            dialog.dismiss();
            mStartVO = vo;
            mView.changeStart(mStartVO.getStrTime());

            /* "结束时间"必需大于"开始时间"，如果不满足条件，需重置mEndVO */
            if (mEndVO != null && mEndVO.timeStmap <= mStartVO.timeStmap) {
                mEndVO = null;
                mView.changeEnd("");
            }

        }).setSelectTime(mStartVO).builder().show();
    }

    @Override
    public void selectEnd() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DAY_OF_MONTH, 2);
        TimeVO maxVO = TimeVO.createFrom(cal.getTimeInMillis());
        if (!isMatchCondition(mStartVO, maxVO)) {
            mView.toast("预约设置时间只能在3天内");
            return;
        }

        new TimeDialog(mView.getContext(), (dialog, vo) -> {
            dialog.dismiss();
            mEndVO = vo;
            mView.changeEnd(mEndVO.getStrTime());

        }).setStartTime(mStartVO) //需要设置开始时间
                .setSelectTime(mEndVO).builder().show();
    }

    /**
     * 是否符合条件
     *
     * @param startVO
     * @param maxVO
     * @return
     */
    private boolean isMatchCondition(TimeVO startVO, TimeVO maxVO) {
        if (startVO == null) return true;
        if (startVO.year <= maxVO.year
                && startVO.month <= maxVO.month
                && startVO.day <= maxVO.day) {
            if (startVO.hour < 23) return true; //注意：是小于23
        }
        return false;
    }

    @Override
    public void clearStart() {
        mStartVO = null;
        mEntity.appointTimeStart = null;
    }

    @Override
    public void clearEnd() {
        mEndVO = null;
        mEntity.appointTimeEnd = null;
    }

    @Override
    public void reqSaveRemindType() {
        int remindType = mEntity.getRemindType();
        String startTimeStamp = mStartVO == null ? "" : String.valueOf(mStartVO.timeStmap);
        String endTimeStamp = mEndVO == null ? "" : String.valueOf(mEndVO.timeStmap);
        mEntity.appointTimeStart = startTimeStamp; // TODO 待修改
        mEntity.appointTimeEnd = endTimeStamp; //TODO 待修改
        mSubscriptions.add(mDutyRepository.reqSaveListenerSetting(remindType, startTimeStamp, endTimeStamp)
                .compose(RxUtil.applySchedulers())
                .doOnSubscribe(() -> mView.showLoadingView(true))
                .doAfterTerminate(() -> mView.hideLoadingView())
                .subscribe(s -> {
                    mDutyRepository.saveListenerSetting(mUserRepository.getLocalDriverUuid(), mEntity); //保存到本地
                    mView.saveRemindTypeSuccess(); //关闭界面
                }, ex -> {
                    showNetworkError(ex, R.string.network_error, mView, mUserRepository);
                }));
    }

    @Override
    public int driverType() {
        return mUserRepository.getDriverType();
    }

}
